package com.xiaodeng.edu.controller;

import cn.hutool.core.bean.BeanUtil;
import com.xiaodeng.edu.interceptors.LoginInterceptor;
import com.xiaodeng.edu.pojo.Result;
import com.xiaodeng.edu.pojo.User;
import com.xiaodeng.edu.pojo.dto.UserDto;
import com.xiaodeng.edu.service.UserService;
import com.xiaodeng.edu.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //用户注册
    @PostMapping("/register")
    public Result register(@Length(min = 6,max = 18,message = "用户名长度必须是6-18位") String username,
                           @Length(min = 6,max = 18,message = "密码长度必须是6-18位") String password)
    {
            userService.register(username,password);
            return Result.success("注册成功");
    }

    //用户登录
    @PostMapping ("/login")
    public Result<String> login(@Validated String username,String password) {
        String token = userService.login(username, password);
        return Result.success("登陆成功",token);
    }

    @LoginInterceptor.GlobalJwtIntercept
    //删除用户
    @DeleteMapping("/delete")
    public Result delete(Integer id){
        userService.delete(id);
        return Result.success("删除成功");
    }

    //用户修改信息
    @LoginInterceptor.GlobalJwtIntercept
    @PatchMapping  ("/update")
    public Result<User> update(@Validated @RequestBody User user){
        userService.update(user);
        return Result.success("修改成功");
    }
    @LoginInterceptor.GlobalJwtIntercept
    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @LoginInterceptor.GlobalJwtIntercept
    //用户修改密码
    @PatchMapping("/updatePwd")
    public Result<User> updatePwd(@RequestBody @Validated UserDto userDto){
        User user = BeanUtil.copyProperties(userDto,User.class);
        String newPwd = userDto.getNewPwd();
        userService.updatePwd(newPwd,user);
        return Result.success("修改成功");
    }
    @LoginInterceptor.GlobalJwtIntercept
    //查询用户信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        //根据用户名查询用户
        Map<String,Object> map = ThreadLocalUtil.get();
        String username =(String) map.get("username");
        System.out.println(username);
        User user = userService.findByUserName(username);
        return Result.success(user);
    }


}

